<?php

class String
{
    private static $pinyins;

    function pinyin ($string, $head = 0, $close = 1)
    {
        $string = iconv('utf-8', 'gbk//ignore', $string);
        $returnString = '';
        $string = trim($string);
        $slen = strlen($string);
        if ($slen < 2)
        {
            return $string;
        }
        if (count(self::$pinyins) == 0)
        {
            $fp = fopen(SYS_PATH . '/data/pinyin.dat', 'r');
            while (! feof($fp))
            {
                $line = trim(fgets($fp));
                self::$pinyins[$line[0] . $line[1]] = substr($line, 3, strlen($line) - 3);
            }
            fclose($fp);
        }
        for ($i = 0; $i < $slen; $i ++)
        {
            if (ord($string[$i]) > 0x80)
            {
                $c = $string[$i] . $string[$i + 1];
                $i ++;
                if (isset(self::$pinyins[$c]))
                {
                    if ($head == 0)
                    {
                        $returnString .= self::$pinyins[$c];
                    }
                    else
                    {
                        $returnString .= self::$pinyins[$c][0];
                    }
                }
                else
                {
                    $returnString .= "_";
                }
            }
            else if (eregi("[a-z0-9]", $string[$i]))
            {
                $returnString .= $string[$i];
            }
            else
            {
                $returnString .= "_";
            }
        }
        if ($close == 0)
        {
            unset(self::$pinyins);
        }
        return $returnString;
    }
}